package com.project.yunshitong.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

public class FileUtils {

    /**
     * 根据Uri获取文件路径
     *
     * @param context 上下文
     * @param uri     Uri
     * @return 文件路径
     */
    public static String getFilePathFromUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }

        String filePath = null;

        // DocumentProvider
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)||isDownloadsDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    filePath = Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    if(type.equals("raw")) {
                        filePath =  split[1];
                        Log.e("TAG", "getFilePathFromUri: ======" + filePath);
                    }else{
                        // 其他存储设备
                        filePath = "/storage/" + type + "/" + split[1];
                    }
                }
            }
            // DownloadsProvider
           /* else if (isDownloadsDocument(uri)) {
                String id = DocumentsContract.getDocumentId(uri);
                Log.e("TAG", "getFilePathFromUri1: iid======"+id );
                if(id.contains("raw:")){
                    id = id.replace("raw:","");
                }
                Log.e("TAG", "getFilePathFromUri2: id======"+id );
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.parseLong(id));

                filePath = getDataColumn(context, contentUri, null, null);
            }*/
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                filePath = getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            filePath = getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        else if ("raw".equalsIgnoreCase(uri.getScheme())) {
            filePath = getFilePathFromRawUri(uri);
        }
        // Special case for API >= 24
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "raw".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }

        return filePath;
    }
    /**
     * 从raw:开头的Uri获取文件路径
     *
     * @param uri Uri
     * @return 文件路径
     */
    private static String getFilePathFromRawUri(Uri uri) {
        if (uri == null) {
            return null;
        }
        return uri.getPath();
    }
    /**
     * 获取数据列的值
     *
     * @param context       上下文
     * @param uri           Uri
     * @param selection     选择条件
     * @param selectionArgs 选择参数
     * @return 数据列的值
     */
    private static String getDataColumn(Context context, Uri uri, String selection,
                                        String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * 判断是否为ExternalStorageProvider
     *
     * @param uri Uri
     * @return 是否为ExternalStorageProvider
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * 判断是否为DownloadsProvider
     *
     * @param uri Uri
     * @return 是否为DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * 判断是否为MediaProvider
     *
     * @param uri Uri
     * @return 是否为MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}


